import { useRequestHandle } from '@/utils/utils';
import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import { ProDescriptions } from '@ant-design/pro-components';
import {
  Button,
  Drawer,
  message,
  Popconfirm,
  Space,
  Switch,
  Tag,
  Tree,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import { Access, useAccess } from 'umi';
import SaveForm from './components/SaveForm';
import styles from './index.less';
import operation from './operation';
import { add, get, getOrganizationTreeSelectData, query, statusChange, update } from './service';
import { Layout } from 'antd';
import ProMaxTable from '@/components/ProMaxTable';


const { Content, Sider } = Layout;
const UserManage = () => {
  const [saveFormVisible, setSaveFormVisible] = useState(false);
  const [updateFormValues, setUpdateFormValues] = useState({});
  const actionRef = useRef();
  const [row, setRow] = useState();
  const { canOperation, canShowOption } = useAccess();
  const [organizationTreeSelectData, setOrganizationTreeSelectData] = useState([]);
  const [organizationId, setOrganizationId] = useState([]);
  // 是否显示操作列
  const isShowOptionColumn = canShowOption([operation.update, operation.delete]);

  // 刷新
  const reload = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  // 新增
  const addRequest = useRequestHandle(add, () => {
    message.success('创建成功.');
    setSaveFormVisible(false);
    reload();
  });
  // 更新
  const updateRequest = useRequestHandle(update, () => {
    message.success('更新成功.');
    setSaveFormVisible(false);
    setUpdateFormValues({});
    reload();
  });

  // 状态变更
  const statusChangeRequest = useRequestHandle(statusChange, () => {
    message.success('操作成功.');
    reload();
  });

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      fixed: 'left',
      width: 75,
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      width: 150,
      render: (dom, entity) => <a onClick={() => setRow(entity)}>{dom}</a>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 100,
      render: (_, record) => {
        const isChecked = record.status === 1;
        const canChangeStatus = canOperation(operation.statusChange) && record.userType !== 2;
        if (!canChangeStatus) {
          return isChecked ? <Tag color="#87d068">启用</Tag> : <Tag color="#f50">禁用</Tag>;
        }
        const title = isChecked ? '确定要禁用该数据吗？' : '确定要启用该数据吗？';
        return (
          <>
            <Popconfirm
              placement="top"
              title={title}
              onConfirm={(e) => {
                e.stopPropagation();
                statusChangeRequest.run({ id: record.id });
              }}
              okText="确定"
              cancelText="取消"
            >
              <Switch
                loading={statusChangeRequest.loading}
                checkedChildren="启用"
                unCheckedChildren="禁用"
                checked={isChecked}
              />
            </Popconfirm>
          </>
        );
      },
    },
   
    {
      title: '手机号',
      dataIndex: 'phoneNumber',
      hideInSearch: true,
      width: 150,
      copyable: true,
    },
    {
      title: '组织架构',
      dataIndex: 'organizationNames',
      hideInDescriptions: true,
      width: 170,
      hideInSearch: true,
      render: (_, entity) => {
        if (entity?.organizationNames?.length > 1) {
          return (
            <Space>
              <Tag key={entity.organizationNames[0]} style={{ cursor: 'pointer' }}>
                {entity.organizationNames[0]}
              </Tag>
              <EllipsisOutlined style={{ cursor: 'pointer' }} onClick={() => setRow(entity)} />
            </Space>
          );
        }
        return (
          <Space>
            {entity?.organizationNames.map((item) => (
              <Tag key={item} style={{ cursor: 'pointer' }}>
                {item}
              </Tag>
            ))}
          </Space>
        );
      },
    },
    {
      title: '职位',
      dataIndex: 'positionNames',
      hideInDescriptions: true,
      width: 170,
      hideInSearch: true,
      render: (_, entity) => {
        if (entity?.positionNames?.length > 1) {
          return (
            <Space>
              <Tag key={entity.positionNames[0]} style={{ cursor: 'pointer' }}>
                {entity.positionNames[0]}
              </Tag>
              <EllipsisOutlined style={{ cursor: 'pointer' }} onClick={() => setRow(entity)} />
            </Space>
          );
        }
        return (
          <Space>
            {entity?.positionNames.map((item) => (
              <Tag key={item} style={{ cursor: 'pointer' }}>
                {item}
              </Tag>
            ))}
          </Space>
        );
      },
    },
    {
      title: '角色',
      dataIndex: 'roleNames',
      hideInDescriptions: true,
      hideInSearch: true,
      width: 170,
      render: (_, entity) => {
        if (entity.roleNames?.length > 1) {
          return (
            <Space>
              <Tag key={entity.roleNames[0]} style={{ cursor: 'pointer' }}>
                {entity.roleNames[0]}
              </Tag>
              <EllipsisOutlined style={{ cursor: 'pointer' }} onClick={() => setRow(entity)} />
            </Space>
          );
        }
        return (
          <Space>
            {entity?.roleNames.map((item) => (
              <Tag key={item} style={{ cursor: 'pointer' }}>
                {item}
              </Tag>
            ))}
          </Space>
        );
      },
    },

    {
      title: '创建时间',
      dataIndex: 'created',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      sorter: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 125,
      fixed: 'right',
      hideInTable: !isShowOptionColumn,
      render: (_, record) => (
        <Space>
          <Access accessible={canOperation(operation.update)}>
            <Button
              type="primary"
              size="small"
              onClick={async () => {
                const result = await get({ id: record.id });
                if (!result.success) {
                  message.error(result.message);
                  return;
                }
                setSaveFormVisible(true);
                setUpdateFormValues(result.data);
              }}
            >
              编辑
            </Button>
          </Access>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    async function init() {
      const response = await getOrganizationTreeSelectData({});
      if (response && response.success) {
        setOrganizationTreeSelectData(response.data);
      } else {
        message.error('获取组织架构错误！');
      }
    }
    init();
  }, []);
  useEffect(() => {
    reload();
  }, [organizationId]);

  return (
    <>
      <Layout>
        <Sider width={300} className={styles.orgTree} theme="light">


          {organizationTreeSelectData.length > 0 ? (
            <Tree
              selectedKeys={[...organizationId]}
              defaultExpandAll
              autoExpandParent
              onSelect={(selectedKeys) => {
                setOrganizationId(selectedKeys);
              }}
              treeData={organizationTreeSelectData}
            />
          ) : null}

        </Sider>
        <Content>
          <ProMaxTable
            headerTitle={<Access key="create" accessible={canOperation(operation.create)}>
              <Button type="primary" onClick={() => setSaveFormVisible(true)}>
                <PlusOutlined /> 创建
              </Button>
            </Access>}
            actionRef={actionRef}
            rowKey="id"
            search={false}

            query={query}
            params={{ organizationId: organizationId.length > 0 ? organizationId[organizationId.length - 1] : '' }}


            columns={columns}
            rowSelection={false}
            expandable={{ defaultExpandAllRows: true }}
          />
        </Content>
        <SaveForm
          onSubmit={async (value) => {
            const params = Object.assign(value, { status: value.status ? 1 : 0 });
            if (params.id) {
              updateRequest.run(params);
            } else {
              addRequest.run(params);
            }
          }}
          onCancel={() => {
            setSaveFormVisible(false);
            setUpdateFormValues({});
          }}
          setRecord={(re) => {
            setUpdateFormValues(re);
          }}
          loading={updateRequest.loading || addRequest.loading}
          modalVisible={saveFormVisible}
          record={updateFormValues}
        />

        <Drawer
          width={600}
          open={!!row}
          onClose={() => {
            setRow(undefined);
          }}
          closable={false}
        >
          {row?.id && (
            <ProDescriptions
              column={2}
              title={row?.realName}
              request={async () => ({
                data: row || {},
              })}
              params={{
                id: row?.id,
              }}
              columns={[
                ...columns,
                {
                  title: '组织架构',
                  dataIndex: 'organizationNames',
                  render: (_, entity) => {
                    return (
                      <Space size={'small'}>
                        {entity.organizationNames?.map((item) => (
                          <Tag key={item} style={{ cursor: 'pointer' }}>
                            {item}
                          </Tag>
                        ))}
                      </Space>
                    );
                  },
                },
                {
                  title: '职位',
                  dataIndex: 'positionNames',
                  render: (_, entity) => {
                    return (
                      <Space size={'small'}>
                        {entity.positionNames?.map((item) => (
                          <Tag key={item} style={{ cursor: 'pointer' }}>
                            {item}
                          </Tag>
                        ))}
                      </Space>
                    );
                  },
                },
                {
                  title: '角色',
                  dataIndex: 'roleNames',
                  render: (_, entity) => {
                    return (
                      <Space size={'small'}>
                        {entity.roleNames?.map((item) => (
                          <Tag key={item} style={{ cursor: 'pointer' }}>
                            {item}
                          </Tag>
                        ))}
                      </Space>
                    );
                  },
                },
              ]}
            />
          )}
        </Drawer>
      </Layout>
    </>
  );
};

export default UserManage;
